package logic

import (
	"autotestservice/testservices/internal/deviceMng"
	"context"
	"gitee.com/jmdvirus/jkgo/jk/jklog"
	"time"

	"autotestservice/testservices/internal/svc"
	"autotestservice/testservices/internal/types"

	"github.com/tal-tech/go-zero/core/logx"
)

type AutotestDeviceConnnectLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

func NewAutotestDeviceConnnectLogic(ctx context.Context, svcCtx *svc.ServiceContext) AutotestDeviceConnnectLogic {
	return AutotestDeviceConnnectLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *AutotestDeviceConnnectLogic) AutotestDeviceConnnect(req types.TestDevice) (*types.Response, error) {
	jklog.L().Debugln("connect device")
	res := &types.Response{
		Code:    0,
		Message: "",
	}
	devOpt := deviceMng.NewDeviceOption(req.ConnectStyle, req.Addr, req.Port)
	findDev := deviceMng.GlobalDeviceMng().Find(*devOpt)
	if findDev == nil {
		jklog.L().Errorf("[%s] not find, create one", req.Addr)
		cmd := deviceMng.DeviceOptionTestCmd{
			Timestamp:   time.Now().Unix(),
			Cmd:         "start",
			Transaction: "",
			PreResult:   "",
		}
		rr, err := devOpt.Connect(cmd)
		if err != nil && rr.Code != 0 {
			res.Code = 10
			res.Message = err.Error()
		} else {
			jklog.L().Debugln("response of device ", rr.Message)
			deviceMng.GlobalDeviceMng().AddNew(*devOpt)
			res.Message = "success"
		}
	} else {
		res.Code = 1
		res.Message = "exist"
	}

	return res, nil
}
